「BZOJ3155|洛谷P4868」Preprefix sum 发表于 2019-04-22 | 分类于 线段树 | | 浏览量: 次 线段树大水题??? 传送门洛谷P4868 BZOJ3155 题解不难发现,如果$A_i$的值增加了$\Delta$,那么$S_i$~$S_n$都增加了$\Delta$。 又$SSi=\sum{i=1}^{i}{S_i}$。 所以直接弄个线段树维护一下就好了。 代码1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#include<cstdio>#include<cstring>using namespace std;typedef long long LL;const int maxn=100005;int n,m,A[maxn];LL S[maxn];char cmd[16];inline int read(){ int ret=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();} while(ch>='0'&&ch<='9'){ret=ret*10+ch-'0';ch=getchar();} return ret*f;}struct SegmentTree{ struct Node{LL Sum,Tag;}Tree[maxn*4]; inline void PushUp(int rt){Tree[rt].Sum=Tree[rt*2].Sum+Tree[rt*2+1].Sum;} inline void PushDown(int rt,int LC,int RC) { if(!Tree[rt].Tag) return; Tree[rt*2].Tag+=Tree[rt].Tag;Tree[rt*2+1].Tag+=Tree[rt].Tag; Tree[rt*2].Sum+=Tree[rt].Tag*LC;Tree[rt*2+1].Sum+=Tree[rt].Tag*RC; Tree[rt].Tag=0; } inline void Build(int L=1,int R=n,int rt=1) { if(L==R){Tree[rt].Sum=S[L];return;} int M=(L+R)>>1; Build(L,M,rt*2); Build(M+1,R,rt*2+1); PushUp(rt); } inline void RangeUpdate(int LL,int RR,int delta,int L=1,int R=n,int rt=1) { if(LL<=L&&R<=RR){Tree[rt].Sum+=(::LL)delta*(R-L+1);Tree[rt].Tag+=delta;return;} int M=(L+R)>>1; PushDown(rt,M-L+1,R-M); if(LL<=M) RangeUpdate(LL,RR,delta,L,M,rt*2); if(M<RR) RangeUpdate(LL,RR,delta,M+1,R,rt*2+1); PushUp(rt); } inline LL RangeQuery(int LL,int RR,int L=1,int R=n,int rt=1) { if(LL<=L&&R<=RR) return Tree[rt].Sum; int M=(L+R)>>1;::LL ret=0; PushDown(rt,M-L+1,R-M); if(LL<=M) ret+=RangeQuery(LL,RR,L,M,rt*2); if(M<RR) ret+=RangeQuery(LL,RR,M+1,R,rt*2+1); return ret; }}ST;int main(){ n=read();m=read(); for(int i=1;i<=n;i++) A[i]=read(); for(int i=1;i<=n;i++) S[i]=S[i-1]+A[i]; ST.Build(); while(m--) { scanf("%s",cmd); if(strcmp(cmd,"Query")==0) { int x=read(); printf("%lld\n",ST.RangeQuery(1,x)); } else { int x=read(),a=read(); ST.RangeUpdate(x,n,a-A[x]); A[x]=a; } } return 0;}